package com.deshan.websys.code.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.deshan.websys.code.mapper.UPFileMapper;
import com.deshan.websys.code.model.UPFile;
import com.deshan.websys.code.service.CmsMinutesService;
import com.deshan.websys.code.utils.ApplicationUtils;
import com.deshan.websys.code.utils.Uploader;

@Service
public class CmsMinutesServiceImpl implements CmsMinutesService {
	@Resource
	UPFileMapper upFileMapper;

	@Override
	public Object uploadMinutes(HttpServletRequest request, MultipartFile file) {

		Uploader up = new Uploader(request);
		String savePath = "D:/upload";
		String virtualurl = "";
		try {
			savePath = ApplicationUtils.getProperty("oss.savepath", "upload");
			virtualurl = ApplicationUtils.getProperty("oss.viewurl", "/ems");
		} catch (Exception ex) {

		}
		// 文件目录
		up.setSavePath(savePath);
		// 虚拟路径
//        up.setVirtualurl(virtualurl);
		String[] fileType = { ".rar", ".doc", ".docx   ", ".zip", ".pdf", ".txt", ".swf", ".wmv", ".avi", ".rm",
				".rmvb", ".mpeg", ".mpg", ".ogg", ".mov", ".wmv", ".mp4", "xls", "xlsx", ".gif", ".png", ".jpg",
				".jpeg", ".bmp" };
		up.setAllowFiles(fileType);
		up.setMaxSize(500 * 1024);

		try {
			up.upload(file);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		String servletPath = request.getServletPath();
		String url = request.getRequestURL().toString();
		String domain = url.replace(servletPath, "");

		String originalName = up.getOriginalName();
		String fileName = up.getFileName();
		String filepath = up.getUrl();
		String filetype = up.getType();
		String filesize = up.getSize();
		String fileurl = virtualurl + filepath.replace(savePath, "");
		String id = fileName.replace(filetype, "");
		UPFile upfile = saveInfo(id, originalName, fileName, filetype, filepath, fileurl, filesize);
		/** 返回name - url */
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", upfile.getFileName());
		jsonObject.put("url", upfile.getFileUrl());

		return jsonObject;
	}

	@Override
	public Object getJSONData(String fileid) {
		return null;
	}

	public UPFile saveInfo(String id, String originalName, String fileName, String fileType, String filePath,
			String fileUrl, String fileSize) {
		UPFile upFile = new UPFile();
		upFile.setFileName(fileName);
		upFile.setOriginalName(originalName);
		upFile.setId(id);
		upFile.setFilePath(filePath);
		upFile.setFileUrl(fileUrl);
		upFile.setFileSize(fileSize);
		upFile.setFileType(fileType);
		int t = upFileMapper.insert(upFile);
		String jsontstr = JSONObject.toJSONString(upFile);
		return upFile;
	}
}
